package controller;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import utils.GIFFileFilter;
import utils.ImageUtils;
import utils.JPGFileFilter;
import utils.PNGFileFilter;
import view.MainFrame;
import dialog.NewFileDialog;

/**
 * Main Controller
 * @author KoinKoin Team
 *
 */
public class MainController {

    /**
     * create a newFile
     * <br> ask for a confirmation before
     */
	public static void newFile() {
		if (MainFrame.getInstance().getDrawingPane() != null) {
			switch (JOptionPane
					.showConfirmDialog(
							null,
							"Do you want to save your current file before creating a new one?",
							"New file", JOptionPane.YES_NO_CANCEL_OPTION)) {

			case JOptionPane.YES_OPTION:
				if (saveFile())
					new NewFileDialog();
				break;

			case JOptionPane.NO_OPTION:
				new NewFileDialog();
				break;
			}
		} else
			new NewFileDialog();
	}

	public static void launchApplication() {
		MainFrame.getInstance();
	}

	/**
	 * close application 
	 * <br> ask for confirmation before
	 */
	public static void closeApplication() {
		if (MainFrame.getInstance().getDrawingPane() == null)
			exit();

		switch (JOptionPane.showConfirmDialog(null, "Save file before exit?",
				"Save", JOptionPane.YES_NO_CANCEL_OPTION)) {

		case JOptionPane.YES_OPTION:
			if (saveFile())
				exit();
			break;

		case JOptionPane.NO_OPTION:
			exit();
			break;
		}

	}

	private static void exit() {
		MainFrame.getInstance().dispose();
		System.exit(0);
	}

	/**
	 * save a file
	 * @return
	 */
	public static boolean saveFile() {

		JFileChooser fc = new JFileChooser(new JFileChooser()
				.getFileSystemView().getDefaultDirectory());
		fc.setSelectedFile(new File(MainFrame.getInstance().getDrawingPane()
				.getDocumentName()));
		fc.addChoosableFileFilter(new PNGFileFilter());
		fc.addChoosableFileFilter(new JPGFileFilter());
		fc.addChoosableFileFilter(new GIFFileFilter());
		int retrival = fc.showSaveDialog(null);
		if (retrival == JFileChooser.APPROVE_OPTION) {
			BufferedImage mix = MainFrame.getInstance().getDrawingPane()
					.mixAll();
			try {
				String extension = fc.getFileFilter().getDescription()
						.substring(2);
				String folder = fc.getSelectedFile().getParent();

				String fileName = fc.getSelectedFile().getName();
				if (fileName.lastIndexOf(".") == -1)
					fileName += "." + extension;
				if (extension.equals("jpg"))
					mix = ImageUtils.fillTransparentPixels(mix, Color.WHITE);
				ImageIO.write(mix, extension,
						new File(folder + "\\" + fileName));
				return true;
			} catch (IOException e) {
				System.err.println("Error while saving the file");
			}
		}

		return false;
	}
}
